/*
 * Copyright (C) 2013 Fabiano Tarlao
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package org.easybenchmark.client.benchmarks;

/**
 *
 * @author Fabiano Tarlao
 */
public class StringCrunchBenchmark extends  Benchmark{
    private StringBuilder destString = new StringBuilder();
    private String brick="ciaociaociaomaramao";
    private int blockSize=brick.length();
    private int WARMUP_LOAD =40;
    private int DEFAULT_BENCHMARK_LOAD=1000;
    private int benchmarkLoad;
    private int currentBenchLoad;

    public StringCrunchBenchmark() {
        this.benchmarkLoad = DEFAULT_BENCHMARK_LOAD;
    }

    public StringCrunchBenchmark(int benchmarkLoad) {
        if(benchmarkLoad<=brick.length()*2){
            throw new IllegalArgumentException("benchmark load has to be higher than "+brick.length()*2);
        }
        this.benchmarkLoad = benchmarkLoad;
    }
    
    
    @Override
    protected int initWarmUpTask() {
        currentBenchLoad=WARMUP_LOAD;
        return currentBenchLoad;
    }

    @Override
    protected int initBenchTask() {
       currentBenchLoad=benchmarkLoad;
       return currentBenchLoad;
    }

    @Override
    protected long benchTask() {
       long currentWorkDone=0;
       //concatenation
       while(destString.length()<currentBenchLoad){
         destString.append(brick);
       }
      currentWorkDone+=destString.length();
      int oldSize=destString.length();
      //remove
      
       while(destString.length()>currentBenchLoad/2){
         int pos=destString.length()/2;
         destString.delete(pos,pos+blockSize);
       }
       
      currentWorkDone += oldSize - destString.length();
      oldSize = destString.length();
      
      //insertion 
       while(destString.length()<currentBenchLoad){
         destString.insert(destString.length()/2,brick);
       }
       currentWorkDone += destString.length()-oldSize;
       
      return currentWorkDone;
    }
    
}
